package com.tmt.paymentcenter.web.configure.bean;

import com.tmt.paymentcenter.web.domain.TradeUser;
import com.tmt.paymentcenter.web.repository.ITradeUserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import tmt.usercenter.web.domain.TmtUser;
import tmt.usercenter.web.domain.security.UserDetailsImpl;

/**
 * Created by ThreeManTeam on 2017/6/14.
 */
@Component
public class UserAuditorAware implements AuditorAware<TradeUser> {

	@Autowired
	private ITradeUserRepo iTradeUserRepo;

	/**
	 * currentUser静态变量只能在初始化数据库基础数据时使用
	 */
	public static TradeUser currentUser = null;

	@Override
	public TradeUser getCurrentAuditor() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null || !authentication.isAuthenticated()) {
			return currentUser;
		}

		TradeUser appUser = null;
		try {
			Long tmtUserId = ((UserDetailsImpl) authentication.getPrincipal()).getUserId();
			Long id = iTradeUserRepo.findIdByTmtUserId(tmtUserId);
			appUser = new TradeUser();
			appUser.setId(id);
		} catch (Exception ex) {
		}

		return appUser;
	}
}
